﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SaturniLibrary.Cache
{
    internal class DictonaryCacheData
    {
        public object Value { get; set; }
        public DateTime ExpiedDate { get; set; }
    }

    public class DictonaryCacheAPI : ICacheAPI
    {
        #region ICacheAPI Members
        private Dictionary<string, DictonaryCacheData> dataList = new Dictionary<string, DictonaryCacheData>(StringComparer.OrdinalIgnoreCase);

        public void Add(string key, object value, int expiredSeconds)
        {
            DictonaryCacheData data;
            if (dataList.ContainsKey(key))
            {
                data = dataList[key];
                data.Value = value;
                if (expiredSeconds > 0)
                {
                    data.ExpiedDate = DateTime.Now.AddSeconds(expiredSeconds);
                }
            }
            else
            {
                data = new DictonaryCacheData();
                data.Value = value;
                data.ExpiedDate = DateTime.Now.AddSeconds(expiredSeconds);
                dataList.Add(key, data);
            }
        }

        public void Remove(string key)
        {
            if (dataList.ContainsKey(key))
            {
                dataList.Remove(key);
            }
        }

        public object Get(string key)
        {
            if (dataList.ContainsKey(key))
            {
                return dataList[key];
            }
            return null;
        }

        public bool Contains(string key)
        {
            return dataList.ContainsKey(key);
        }

        public long Size()
        {
            return dataList.Count;
        }

        public void Flush()
        {
            dataList.Clear();
        }

        public void Update(string key, object value, int expiredSeconds)
        {
            Add(key, value, expiredSeconds);
        }
        #endregion
    }
}
